/*
 * Copyright 2012-2022 guoyangyun.com All right reserved. This software is the confidential and proprietary information
 * of guoyangyun.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it
 * only in accordance with the terms of the license agreement you entered into with guoyangyun.com.
 */
package com.lening.provider.service.impl.smsImpl;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类SendSmsoto.java的实现描述：
 * 
 * @author t104 2022年11月11日 下午2:49:49
 */
public class SendSmsoto {

    public static void sendSms(String phone) {
        String host = "http://api.guoyangyun.com";
        String path = "/api/sms/smsmtm.htm";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appkey", "204583801");
        paramMap.put("appsecret", "IGC0YrCyhft8oGdry8ggRKT9EU8yWzla");
        paramMap.put("smsSignId", "db5349c52117461199c289524a0a1b43"); // 签名ID
        paramMap.put("templateId", "ef1bd3b6e3c4471cb3c79d590e6e484f"); // 模板ID
        paramMap.put("mobile", phone); // 手机号码
//        paramMap.put("param", phone); // 变量 格式 k:v,k:v 例如[**code**:8372]

        postTest(host, path, paramMap);
        // getTest(host, path, paramMap);
    }

    public static void getTest(String host, String path, Map<String, String> paramMap) {

        try {
            HttpResponse response = doGet(host, path, paramMap);
            System.out.println(response);
            // response body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void postTest(String host, String path, Map<String, String> paramMap) {

        try {
            HttpResponse response = doPost(host, path, paramMap);
            System.out.println(response);
            // response body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * get
     * 
     * @param host
     * @param path
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path,
                                     Map<String, String> querys) throws Exception {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(buildUrl(host, path, querys));

        return httpClient.execute(request);
    }

    /**
     * post form
     * 
     * @param host
     * @param path
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path,
                                      Map<String, String> bodys) throws Exception {
        HttpClient httpClient = HttpClients.createDefault();

        HttpPost request = new HttpPost(buildUrl(host, path, null));

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path,
                                   Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

}
